<template>
	<dt-main-body v-model="labelPosition">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>系统管理</el-breadcrumb-item>
				<el-breadcrumb-item>编辑频道</el-breadcrumb-item>
			</el-breadcrumb>
		</div>

		<div class="content-box">
			<el-tabs v-model="activeName" type="card">
				<el-tab-pane label="基本信息" name="info">
					<div class="tab-content">
						<el-form ref="editForm" :model="model" :rules="rules" :label-position="labelPosition" label-width="120px">
							<el-form-item prop="siteId" label="所属站点">
								<el-select v-model="model.siteId" :disabled="model.id>0" placeholder="请选择...">
									<el-option v-for="site in siteList"
											   :key="site.id"
											   :label="site.title"
											   :value="site.id">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="name" label="频道标识">
								<el-input v-model="model.name" :disabled="model.id>0" placeholder="只允许英文字母数字"></el-input>
							</el-form-item>
							<el-form-item prop="title" label="频道标题">
								<el-input v-model="model.title" placeholder="任意字符，255个字符内"></el-input>
							</el-form-item>
							<el-form-item prop="sortId" label="排序数字">
								<el-input v-model="model.sortId" placeholder="数字越小越排前"></el-input>
							</el-form-item>
							<el-form-item label="是否启用">
								<el-switch :active-value="0" :inactive-value="1" v-model="model.status"></el-switch>
							</el-form-item>
							<el-form-item label="允许评论">
								<el-switch :active-value="1" :inactive-value="0" v-model="model.isComment"></el-switch>
							</el-form-item>
							<el-form-item label="开启相册">
								<el-switch :active-value="1" :inactive-value="0" v-model="model.isAlbum"></el-switch>
							</el-form-item>
							<el-form-item label="开启附件">
								<el-switch :active-value="1" :inactive-value="0" v-model="model.isAttach"></el-switch>
							</el-form-item>
							<el-form-item label="允许投稿">
								<el-switch :active-value="1" :inactive-value="0" v-model="model.isContribute"></el-switch>
							</el-form-item>
						</el-form>
					</div>
				</el-tab-pane>
				<el-tab-pane label="扩展字段" name="filed">
					<div class="tab-content">
						<el-row>
							<el-col :span="24">
								<el-button type="primary" size="small" icon="el-icon-plus" @click="editRow">添加</el-button>
								<el-button type="danger" size="small" icon="el-icon-delete" @click="removeRow">删除</el-button>
							</el-col>
						</el-row>
						<el-card class="table-card" style="margin-top:20px;">
							<el-table ref="fieldTable" :data="model.fields" style="width:100%;" @selection-change="handleSelectionChange">
								<el-table-column type="selection" width="55"></el-table-column>
								<el-table-column min-width="120" prop="name" label="字段名"></el-table-column>
								<el-table-column min-width="150" prop="title" label="标题"></el-table-column>
								<el-table-column min-width="100" label="控件类型">
									<template slot-scope="scope">
										<el-tag size="small" type="success" v-if="scope.row.controlType=='input'">单行文本</el-tag>
										<el-tag size="small" type="info" v-if="scope.row.controlType=='textarea'">多行文本</el-tag>
										<el-tag size="small" type="success" v-if="scope.row.controlType=='editor'">编辑器</el-tag>
										<el-tag size="small" type="danger" v-if="scope.row.controlType=='images'">图片上传</el-tag>
										<el-tag size="small" type="success" v-if="scope.row.controlType=='video'">视频上传</el-tag>
										<el-tag size="small" type="info" v-if="scope.row.controlType=='datetime'">时间日期</el-tag>
										<el-tag size="small" type="warning" v-if="scope.row.controlType=='radio'">单选框</el-tag>
										<el-tag size="small" type="danger" v-if="scope.row.controlType=='checkbox'">复选框</el-tag>
									</template>
								</el-table-column>
								<el-table-column width="80" label="必填" align="center">
									<template slot-scope="scope">
										<i class="el-icon-check" v-if="scope.row.isRequired===1"></i>
										<i class="el-icon-minus" v-else></i>
									</template>
								</el-table-column>
								<el-table-column fixed="right" width="80" label="编辑" align="center">
									<template slot-scope="scope">
										<el-link icon="el-icon-edit-outline" @click="editRow(scope.$index, scope.row)"></el-link>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
						<el-dialog title="扩展字段" @close="resetDialog" :destroy-on-close="true" :visible.sync="dialogFieldVisible" fullscreen>
							<el-form ref="fieldForm" :model="field" :rules="rules" :label-position="labelPosition" label-width="120px">
								<el-form-item label="字段列名" prop="name" :rules="rules.fields.name">
									<el-input v-model="field.name" placeholder="只允许英文下划线"></el-input>
								</el-form-item>
								<el-form-item label="字段标题" prop="title" :rules="rules.fields.title">
									<el-input v-model="field.title" placeholder="任意字符，128个字符内"></el-input>
								</el-form-item>
								<el-form-item label="控件类型" prop="controlType" :rules="rules.fields.controlType">
									<el-select v-model="field.controlType" placeholder="请选择类型...">
										<el-option label="单行文本" value="input"></el-option>
										<el-option label="多行文本" value="textarea"></el-option>
										<el-option label="编辑器" value="editor"></el-option>
										<el-option label="图片上传" value="images"></el-option>
										<el-option label="视频上传" value="video"></el-option>
										<el-option label="时间日期" value="datetime"></el-option>
										<el-option label="单选框" value="radio"></el-option>
										<el-option label="复选框" value="checkbox"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item v-if="field.controlType=='editor'" label="编辑器类型">
									<el-radio-group v-model="field.editorType">
										<el-radio-button label="0">标准型</el-radio-button>
										<el-radio-button label="1">简洁型</el-radio-button>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="是否必填">
									<el-switch :active-value="1" :inactive-value="0" v-model="field.isRequired"></el-switch>
								</el-form-item>
								<el-form-item v-if="field.controlType=='input'" label="是否密码框">
									<el-switch :active-value="1" :inactive-value="0" v-model="field.isPassword"></el-switch>
								</el-form-item>
								<el-form-item v-if="field.controlType=='radio'||field.controlType=='checkbox'" label="选项列表" prop="itemOption" :rules="rules.fields.itemOption">
									<el-input type="textarea" v-model="field.itemOption" placeholder="选项名称|值，以回车换行为一行。"></el-input>
								</el-form-item>
								<el-form-item label="默认值">
									<el-input v-model="field.defaultValue" :placeholder="field.controlType=='checkbox'?'初始化默认值,多个默认值用逗号分开，例如：1,2,5':'初始化默认值'"></el-input>
								</el-form-item>
								<el-form-item label="排序数字" prop="sortId" :rules="rules.fields.sortId">
									<el-input v-model="field.sortId" placeholder="数字越小越排前"></el-input>
								</el-form-item>
								<el-form-item label="验证提示">
									<el-input v-model="field.validTipMsg" placeholder="表单验证提示信息"></el-input>
								</el-form-item>
								<el-form-item label="错误提示">
									<el-input v-model="field.validErrorMsg" placeholder="表单验证错误信息"></el-input>
								</el-form-item>
								<el-form-item label="正则表达式">
									<el-input v-model="field.validPattern" placeholder="表单验证正则表达式"></el-input>
								</el-form-item>
							</el-form>
							<div slot="footer" class="dialog-footer">
								<el-button type="primary" icon="el-icon-edit" @click="submitField">确 定</el-button>
								<el-button type="warning" @click="dialogFieldVisible = false">取 消</el-button>
							</div>
						</el-dialog>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
		
		<div class="footer-box">
			<div class="footer-btn">
				<el-button type="primary" @click="submitForm">确认保存</el-button>
				<el-button plain @click="$common.back()">返回上一页</el-button>
			</div>
		</div>
	</dt-main-body>
</template>

<script>
	export default {
		props: {
			id: 0
		},
		data() {
			return {
				activeName: 'info', //当前选项卡
				labelPosition: 'right', //表单对齐方式
				dialogFieldIndex: -1,//正在编辑的索引号
				dialogFieldVisible: false,//编辑对话框
				siteList: [],//站点列表
				multipleSelection: [],
				model: {
					id: 0,
					siteId: null,
					name: '',
					title: '',
					isComment: 0,
					isAlbum: 0,
					isAttach: 0,
					isContribute: 0,
					sortId: 99,
					status: 0,
					fields: []
				},
				field: {
					id: 0,
					channelId: 0,
					name: null,
					title: null,
					controlType: null,
					itemOption: null,
					defaultValue: null,
					isPassword: 0,
					isRequired: 0,
					editorType: 0,
					validTipMsg: null,
					validErrorMsg: null,
					validPattern: null,
					sortId: 99
				},
				rules: {
					siteId: [
						{ required: true, message: '请选择所属站点', trigger: 'change' }
					],
					name: [
						{ required: true, message: '请输入频道名称', trigger: 'blur' },
						{ min: 2, max: 128, message: '长度在 2 到 128 个字符', trigger: 'blur' },
						{ pattern: /^[a-zA-Z_]{1,}$/, message: '只能字母和下划线', trigger: 'blur' }
					],
					title: [
						{ required: true, message: '请输入频道标题', trigger: 'blur' },
						{ min: 2, max: 128, message: '长度在 2 到 128 个字符', trigger: 'blur' }
					],
					sortId: [
						{ required: true, message: '请输入排序数字', trigger: 'blur' }
					],
					fields: {
						name: [
							{ required: true, message: '请填写字段名称', trigger: 'blur' },
							{ min: 2, max: 128, message: '长度在 2 到 128 个字符', trigger: 'blur' },
							{ pattern: /^[a-zA-Z0-9_]{1,}$/, message: '只能字母数字和下划线', trigger: 'blur' }
						],
						title: [
							{ required: true, message: '请输入字段标题', trigger: 'blur' },
							{ min: 2, max: 128, message: '长度在 2 到 128 个字符', trigger: 'blur' }
						],
						controlType: [
							{ required: true, message: '请选择控件类型', trigger: 'change' }
						],
						itemOption: [
							{ required: true, message: '请填写选择列表', trigger: 'change' }
						],
						sortId: [
							{ required: true, message: '请输入排序数字', trigger: 'blur' }
						]
					}
				}
			}
		},
		methods: {
			//加载数据
			async loadData() {
				let _this = this; //当前页面
				//加载站点列表
				await _this.$api.request({
					url: '/admin/site/view/0',
					loading: true,
					success(res) {
						_this.siteList = res.data;
					}
				});
				//初始化数据
				await _this.initData();
			},
			//初始化数据
			async initData() {
				let _this = this; //当前页面
				if (_this.id > 0) {
					await _this.$api.request({
						url: `/admin/channel/${_this.id}`,
						loading: true,
						success(res) {
							//赋值给model
							Object.keys(_this.model).forEach(key => { _this.model[key] = res.data[key] });
						}
					});
				}
				
			},
			//表单提交
			submitForm() {
				let _this = this; //当前页面
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['editForm'].validate((valid) => {
						if (valid) resolve()
					});
				});
				Promise.all([f1]).then(() => {
					//提交表单,Id大于0则修改，否则添加
					if (_this.model.id > 0) {
						_this.$api.request({
							method: 'put',
							url: '/admin/channel/' + _this.model.id,
							data: _this.model,
							loading: true,
							successMsg: '修改频道已成功',
							success(res) {
								//重新加载菜单
								_this.$emit('loadMenu'); //通知父组件更新
								//可跳转加列表页
								_this.$common.linkUrl('/setting/channel/list');
							}
						});
					} else {
						_this.$api.request({
							method: 'post',
							url: '/admin/channel',
							data: _this.model,
							loading: true,
							successMsg: '新增频道已成功',
							success(res) {
								//重置表单
								_this.$refs['editForm'].resetFields();
								_this.model.fields = null;
								//重新加载菜单
								_this.$emit('loadMenu'); //通知父组件更新
							}
						});
					}
				})
			},
			//删除扩展字段
			removeRow() {
				let _this = this; //当前页面
				let list = _this.multipleSelection; //拿到选中的数据
				if (list) {
					list.forEach((item, index) => {
						//遍历源数据
						_this.model.fields.forEach((v, i) => {
							//如果选中数据和源数据的某一条唯一标识符相等，删除对应的源数据
							if (item == v) {
								_this.model.fields.splice(i, 1);
							}
						})
					});
				}
				//清除选中状态
				_this.$refs.fieldTable.clearSelection();
			},
			//新增编辑扩展字段
			editRow(i, item) {
				let _this = this; //当前页面
				_this.dialogFieldVisible = true;
				_this.$nextTick(() => {
					//如果有值则修改
					if (typeof i === 'number' && !isNaN(i)) {
						//赋值给model
						Object.keys(_this.field).forEach(key => { _this.field[key] = item[key] });
						_this.dialogFieldIndex = i;
					}
				});
				
				
			},
			//提交扩展字段
			submitField() {
				let _this = this; //当前页面
				//表单验证
				_this.$refs['fieldForm'].validate((valid) => {
					if (valid) {
						if (_this.dialogFieldIndex >= 0) {
							//赋值给扩展字段
							Object.keys(this.field).forEach(key => {
								_this.model.fields[_this.dialogFieldIndex][key] = this.field[key]
							});
						} else {
							//检查字段是否重复
							let findObj = _this.model.fields.find(item => item.name == _this.field.name);
							if(findObj) {
								_this.$message({ type: 'warning', message: '字段名称已重复，请修改重试' });
								return false;
							}
							//注意要重新创建一个对象复制，直接赋值的话拿到的是空值
							var obj = JSON.parse(JSON.stringify(_this.field));
							_this.model.fields.push(obj);
						}
						this.dialogFieldVisible = false;
					} else {
						return false;
					}
				});
			},
			//关闭弹窗及重置字段
			resetDialog() {
				this.dialogFieldIndex = -1;
				this.$refs['fieldForm'].resetFields();
			},
			//扩展字段选中事件
			handleSelectionChange(val) {
				this.multipleSelection = val;
			}
		},
		created() {
			//初始化数据
			this.loadData();
		}
	}
</script>

<style lang="scss">
</style>